<?php
namespace app\push\controller;
use Workerman\Worker;
use Workerman\Lib\Timer;


class Index
{
    private $s=30;
    private $type = 1;//1💪 强壮，2，下注，3，开住，4发放
    private $ai;
    public function index()
    {
        // 创建一个Worker监听2346端口，使用websocket协议通讯
        $ws_worker = new Worker("websocket://0.0.0.0:2346");
        // 启动1个进程对外提供服务
        $ws_worker->count = 1;
        
        $ws_worker->onConnect = function ($connection){
            echo "有人链接游戏\n";
        };
        
        //设置心跳保持连接
        $ws_worker->onWorkerStart = function($worker) {
            Timer::add(5, function()use($worker){
                $time_now = time();
                foreach($worker->connections as $connection) {
                    // 有可能该connection还没收到过消息，则lastMessageTime设置为当前时间
                    if (empty($connection->lastMessageTime)) {
                        $connection->lastMessageTime = $time_now;
                        continue;
                    }
                    // 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
                    if ($time_now - $connection->lastMessageTime > 600) {
                        $connection->close();
                    } 
                }
                $this->deteteHome($worker->connections);
            });
               
                Timer::add(1, function()use($worker){

                    $s = date("His");
                    if($s == "201111"||$s == "211111"||$s == "221111"||$s == "231111"||$s == "001111"||$s == "011111"||$s == "021111"){
                        $conModel = db("config");
                        $conf = $conModel->where("id=5")->find();
                        $co  = $conf['values']-1000;
                        
                        $array = ["values"=>$co];
                        $conModel->where("id=5")->update($array);
                    }
                    
                    
                    
                    //时间计时
                    $this->jishi($worker);
                    
                });
        };
        // 当收到客户端发来的数据后返回hello $data给客户端
        $ws_worker->onMessage = function($connection, $data)
        {     
            
                
           
                $action = actionAll();//注册方法
                
                
               
                
                
                $json = checkJson($data,$action);//验证数据格式
                if($json['ok']=="1"){
                    $message = $json['content'];
                    $ckey = isset($connection->key)?$connection->key:0;
                    $bool = ckeckSign($ckey,$message);//验证数据的加密信息
                    if($bool){
                        if($message['ws']!=1){
                            echo "---------客户端发送数据---------".$data."\n";
                        }
                        if($message['ws']<20&&$action[$message['ws']]){//公共方法操作
                            $return = $action[$message['ws']]($message,$connection);//处理数据
                            if($message['ws'] == "10"&&$return['ok']=='1'){//如果是客户登陆，修改链接的id
                                //1初始化通信密钥
                                $key = create_startkey();
                                $connection->key = $key;
                                $return['key'] = $connection->key;
                                foreach ($connection->worker->connections as $con){
                                    if(isset($con->uid)){
                                        if($con->uid==$return['id']){
                                            $con->close();
                                        }
                                    }
                                }
                                $connection->uid = $return['id'];
                                
                               $users=redisd()->HKeys('user');
                              if(!in_array($return['id'], $users)){
                                  $userdata=db('users')->where('id='.$return['id'])->find();
                                  $dd=redisd()->HSet('user',$return['id'],$userdata);
                              }
                              
                              
                              
                                echo $connection->uid."-------登录成功\n";
                            }
                
                             
                
                        }else if($action[$message['ws']]){
                            $message['s'] = $this->s;
                            $message['t'] = $this->type;
                            $return = $action[$message['ws']]($message,$connection);//处理数据
                            if($message['ws']==24||$message['ws']==22){
                                if (isset($connection->homeid)){                                    
                                    echo $connection->uid."加入房间".$connection->homeid."\n";
                                }
                            }
                        }
                        $connection->lastMessageTime = time();
                    }else{
                        $return = array("ok"=>"2","content"=>"加密验证不通过");
                    }
                }else{
                    $return = $json;
                }
                if(isset($return['ws'])&&$return['ws']!=1){
                    $os = json_encode($return);
                    echo "---------回执信息---------".$os."\n";
                }
                $return = json_encode($return);
                
                $connection->send($return);
            
           
        }; 
      $ws_worker->onClose = function($connection){//又玩家推出游戏
            if(isset($connection->uid)){
                echo $connection->uid." login out \n";
            }else{
                echo $connection->id." login out \n";
            }
            $home_userModel = db("home_user");
            if(isset($connection->homeid)){
                $home_userModel->where("home_id={$connection->homeid} and user_id={$connection->uid}")->update(array(
                    "last_time"=>time()
                ));
            }
        };
        // 运行worker
        Worker::runAll();

    }
    
    private function deteteHome($connections){
        $homeModel = db("home");
        $home_userModel = db("home_user");
        $homelist = $homeModel->select(); 
        $time = time();
        foreach ($homelist as $home){
            $num = 2;
            foreach ($connections as $con){
                if(isset($con->homeid)){
                    if($con->homeid==$home['id']){
                        $num = 1;
                        break;
                    }
                }
                
            }
            
            if($num==2){
                
                $t = $time-$home['create_time'];
                if($t>180){
                    if($home['id']!=1){
                        $homeModel->where("id={$home['id']}")->delete();
                    }
                    $home_userModel->where("home_id={$home['id']}")->delete();   
                }
                
            }
        } 
    }
    
    
    /**
     * 计时器，按照计时器计算
     * @param unknown $worker
     */
    private function jishi($worker){
//         $homeModel = db("home");
        $m = $this->s;
        $this->s = $m-1;
        $a = $this->type;
        if($a==1&&$m==20){
            $conModel = db("config");
            $co = $conModel->where("id=9")->find();
            $this->ai = $co['values'];
       
        }
        if($m<=0){
           $data = array();
            $a = $this->type;
            if($a==1){
                echo "开始强壮\n";
                //抢庄结束修改逻辑发送
                $this->s = 45;
                $this->type = 2;   
                //发送开始下注
            }else if($a==2){
                //下注结束修改逻辑发送 
                $this->s = 5;
                $this->type = 3;
                //发送开始转骰子
                
                //计算订单，计算金额，随机点数-----------------------------------------
                
                //1计算每个房间的点数 房间的计算
                $this->createHomeDian();
                //2大厅计算
                $this->createRootDain();
                echo "大厅计算完毕\n";
                //计算每个人的输赢
                $this->setOrderStatus();
            }else if($a==3){
                echo "开始开奖\n";
                //开住结束修改逻辑发送
                $this->s = 10;
                $this->type = 4;
                //计算结束 发放点数，发钱
                $this->sendMoneyAll($worker);
            }else if($a==4){
                //结算    
                $this->s = 30;
                $this->type = 1;
                //更新期数计时器
                $conModel = db("config");
                $co = $conModel->where("id=2")->find();
                $num = $co['values'];
                $num = $num+1;
                $conModel->where("id=2")->update(array("values"=>$num));
               
                
                $connecitons = $worker->connections;
                //判断用户是否掉线
               
                $arrayuser=array();
                foreach($connecitons as $con){
                    if(isset($con->uid)){
                        array_push($arrayuser, $con->uid);
                    }
                } 
//                 dump($arrayuser);
                $homeUser=redisd()->HgetAll('homeUser');//二维数组
                foreach ($homeUser as $ks=>$w){
                    foreach($w as $key=>$s){
                        if(!in_array($s,$arrayuser)){
                            echo $s."不在线删\n";
                            unset($w[$key]);
                        }
                    }
                    redisd()->HSet('homeUser', $ks, $w);
                    
                }
                
                
                
                //删除房间订单表和房间信息
                $homeidArray=redisd()->HgetAll('homes');//房间的id key
                if($homeidArray){
                    foreach($homeidArray as $k=>$hd){
                        redisd()->del('order'.$k.'7');//当前房间小点的用户id
                        redisd()->del('order'.$k.'8');//当前房间小点的用户id
                        $homeUsers=redisd()->HGet('homeUser',$k);//获取房间内的人
                        echo count($homeUsers);
                        if($k!=1&&count($homeUsers)==0){
                            echo "成功删除房间{$k}\n";
                            redisd()->HDel('homes',$k);
                            redisd()->HDel('homeUser',$k);
                        }
                    }
                }
                 
                
                
                
                
                
                
                
                
                //查询每个人的信息是否可以自动坐庄，或者是否掉线
//                 $zHomes = $homeModel->where("id>0 and role_user_id>0")->select();
                $zHomes = redisd() -> HgetAll("homes");
//                 $userModel = db("users");
                $duanHome = "";
                foreach ($zHomes as $k => $h){
                    if ($h['role_user_id'] > 0){
                        $home_role = $h['role_user_id'];
                        //判断客户是否在线
                        //在线执行，判断钱数是否可以继续坐庄
                        if(is_login($worker,$home_role)){
                            //上期押注的金额
                            $zmoney =  $h['rolemoney'];
//                             $ouser = $userModel->field("user_money,user_type")->where("id={$home_role}")->find();
                            $ouser = redisd() -> HGet("user", $home_role);
                            if($ouser['user_money']<$zmoney||($ouser['user_type']==1)||$zmoney<1000){
                                $duanHome .= ",".$k;
                            }else{
                                //继续坐庄
                                //发送数据到客户端可以下庄
                                $array = array(
                                    "ws"=>85,
                                    "ok"=>1
                                );
                                $array1 = array("ws"=>86,"ok"=>1,"money"=>$h['rolemoney']);
                                sendByHomeIdAndWorker($worker,$k,$array1);
                                sendById($worker,$home_role,$array);   
                            }
                        }else{
                            $duanHome .= ",".$k;
                        }
                    }
                }
                
                $duanHome = trim($duanHome,",");
                //删除条件不满足的庄家，重新抢庄
                if($duanHome){ 
//                     $homeModel->where("id in ({$duanHome})")->update(array("role_user_id"=>0,"rolemoney"=>0));
                    $duans = explode(",", $duanHome);
                    $array = array("ws"=>86,"ok"=>1,"money"=>0);
                    foreach ($duans as $v){
                        $Uhomes = redisd() -> HGet("homes", $v);
                        $Uhomes['role_user_id'] = 0;
                        $Uhomes['rolemoney'] = 0;
                        redisd() -> HSet("homes",$v, $Uhomes);
                        sendByHomeIdAndWorker($worker,$v,$array);
                    }
                }
                
                //如果退出房间超过了30分钟将退出房间，删除这个人在房间的信息
                /* $home_userModel = db("home_user");
                $time = time()-1800;
                $home_userModel->where("last_time<{$time} and last_time>0")->delete(); */
                //机器人下注金额归零
                $model= db("ai");
                $js = $model->where("id=1")->update(array("num"=>0));
            }
            
            //更新所有房间人物的时间阶段信息
            $data['ws'] = 60;
            $data['miao'] = $this->s;
            $data['t'] = $this->type;
            sendAllConnections($worker, $data);
        }
        if($this->ai==1){
            $userModel = db("users");
            $users = $userModel->where("user_type=1 and user_money>=1000")->select();
            $user = $users[rand(0,count($users)-1)];
            $home = redisd() -> HGet("homes",1);

            //机器人抢庄
            if($this->type==1&&$this->s==5){
                
                if($home['role_user_id']==0){
                    echo "机器人抢庄\n";
                    jiqizhuang($worker,$user);
                }
            }
          
            //大厅房间机器人自动下注
            /* $home = $homeModel->where("id=1")->find(); */
            $home= redisd()->HGet('homes',1);
            $u = $userModel->where("id={$home['role_user_id']}")->find();
            if($this->type==2&&$home['role_user_id']>0){
                    $s = $this->s;
                    $y = $s%2;
                    if($s>10&&$y==1){
                        echo "机器人下注\n";
                        //下注
                        $user = $users[rand(0,count($users)-1)];
                        
                        aiBet($worker,$u);
                    }
            } 
        }
    }
    
    
    
    
    /**
     * 发放每个房间的点数
     * @param unknown $homeModel
     */
    private function createHomeDian(){
        $homeModel=redisd()->HgetAll('homes');
       
        
        if(count($homeModel)>=1){
            $dianModel = db("dian");
            $num = getNum();
            
            $a = rand(1,6);
            $b = rand(1,6);
            $c = rand(1,6); 
        
            foreach ($homeModel as $key=>$home){
                if($key!=1){
                    $array = array(
                        "home_id"=>$key,
                        "num"=>$num,
                        "dian"=>$a."-".$b."-".$c,
                        "add_time"=>time()
                    
                    );
                    $dianModel->insert($array);
                }
               
            }
        }
        
        
    }
    
    /**
     * 计算大厅的点数
     */
    private function createRootDain(){
        $dianModel = db("dian");
   
        //获取庄家id
        $redis=redisd();
        $home=$redis->HGet('homes',1);
        $userid=$home['role_user_id'];
        $num = getNum();
        
        $user = db("users")->where("id={$userid}")->find();
        
        $conModel = db("config");
        $zuida = $conModel->where("id=4")->find();
        $zui = $zuida['values'];//最大数值
        $jishu = $conModel->where("id=5")->find();
        $jis = $jishu['values'];//基数
        
       
        //判断是否是机器人坐庄
       /*  if($user['user_type']==1){ */
            $daKey= redisd() -> HKeys("order18");//获取大小key
            $xiaoKey= redisd() -> HKeys("order17");
            $ymoney=0;
            $smoney=0;
            if($daKey){
                foreach($daKey as $v){
                    $arr=explode('_', $v);
                    if($arr[0]!='jq'){
                       $dalist=redisd() -> HGet("order18",$v);
                        foreach($dalist as $s){
                            $ymoney+=$s;
                        }
                    }
                    
                } 
            }
            if($xiaoKey){
                foreach($xiaoKey as $vl){
                    $arr=explode('_', $vl);
                    if($arr[0]!='jq'){
                        $xiaolist=redisd() -> HGet("order17",$vl);
                        foreach($xiaolist as $sl){
                            $smoney+=$sl;
                        }
                    }
            
                }
            }
            
            $status = 1;
            $money = 0;
            if($ymoney>$smoney){
                $status = 2;
                $money = $ymoney-$smoney;
            }else{
                $status = 3;
                $money = $smoney-$ymoney;
            }
            $a = 1;
            //可以赢钱
            if(($money+$jis)<$zui){
                $a=2;
            }
            //可以输钱
            $fzui = $zui-$zui-$zui;
            if(($jis-$money)>$fzui){
                $a=3;
            }
            
            if($a==1){
                $a=2;
            }
            $daxiao = 0;//一大，2小
            //赢钱
            if($a==2){
                if($status==2){
                    $daxiao = 1;
                }else{
                    $daxiao = 2;
                }
                
            
                $conModel->where("id=5")->update(array("values"=>($jis+$money)));
                
                
            }else if($a==3){
            //输钱
                if($status==2){
                    $daxiao = 2;
                }else{
                    $daxiao = 1;
                }
             
               $conModel->where("id=5")->update(array("values"=>($jis-$money)));
            }
            //计算所有点
            $ay = getdian();
            $dian = "";
           
            if($daxiao==1){
                   $dian=$ay[rand(0,104)];
            }else{
                   $dian=$ay[rand(105,108)];
            }
            $array = array(
                "home_id"=>1,
                "num"=>$num,
                "dian"=>$dian,
                "add_time"=>time()
            );
            
            
       /*      
        //有人坐庄计算
        }else{ 
            $a = rand(1,6);
            $b = rand(1,6);
            $c = rand(1,6); 
           
            $array = array(
                "home_id"=>1,
                "num"=>$num,
                "dian"=>$a."-".$b."-".$c,
                "add_time"=>time()
            );
        }*/
       
        $dianModel->insert($array);
    }
    
    /**
     * 计算下注的人的记录
     */
    private function setOrderStatus(){
        $num = getNum();
        $orderModel = db("order");
        $dianModel = db("dian");
        $userModel = db("users");
        //本期所有非机器人下注的订单
        
        //计算除了机器人下注的所有订单   插入到数据库当中
        
        /* 1.获取到所有房间信息key值
         * 
         * 2.用key去查当前房间里面的 下注信息
         * 
         * 
         *  */
        //1.homes  key
        $homesKey=redisd()->HKeys('homes');
        //2.用key去查当前房间里面的 下注信息
        $orderxiao=0;
        $orderda=0;
        $orderData=array(
            'add_time'=>time(),
            'num'=>$num,
            'is_winning'=>0,
            'order_type'=>0,
        );
        if(count($homesKey)>0){
            foreach($homesKey as $v){
               $xiaoUserId= redisd()->HKeys('order'.$v.'7');//当前房间小点的用户id
              
               //xiao
               if($xiaoUserId){//下注了
                   foreach($xiaoUserId as $s){
                       $useridArray=explode('_', $s);
                       if($useridArray[0]!='jq'){
                           $order=redisd()->HGet('order'.$v.'7', $s);//获取到当前房间下当前用户的 大小点下注记录
                           $orderxiao=array_sum($order);//当前用户下小点订单总和
                           if($orderxiao&&$s>0){
                                   $orderData['user_id']=$s;
                                   $orderData['home_id']=$v;
                                   $orderData['money']=$orderxiao;
                                   $orderData['dian']=7;
                                   $orderModel->insert($orderData);
                               
                           }
                       }
                     
                   } 
               }
               
               
               
               
               $daUserId= redisd()->HKeys('order'.$v.'8');//当前房间大点的用户id
               //da
               if($daUserId){//下注了
                   foreach($daUserId as $ds){
                       $order=redisd()->HGet('order'.$v.'8', $ds);//获取到当前房间下当前用户的 大小点下注记录
                       $orderda=array_sum($order);//当前用户下小点订单总和
                       if($orderda && $ds>0){
                          
                               $orderData['user_id']=$ds;
                               $orderData['home_id']=$v;
                               $orderData['money']=$orderda;
                               $orderData['dian']=8;
                               $orderModel->insert($orderData);
                          
                       }
                   }
               }
               
               
            }
        }
        
        
        
        $orderList = $orderModel->where("is_winning=0 and num={$num} and order_type=0")->select();
        //本期所有的开住记录
        $dianList = $dianModel->where("num={$num}")->select();
        $ids = "";
        foreach ($orderList as $order){
            $orderid = $order['id'];
            $homeid= $order['home_id'];
            foreach ($dianList as $dian){
                if($homeid==$dian['home_id']){
                    $d = $dian['dian'];
                    $ds = explode("-", $d);
                    
                    $diannum = $ds[0]+$ds[1]+$ds[2];
                    if($ds[0]==$ds[1]&&$ds[1]==$ds[2]){
                        
                    }else{
                        if($order['dian']==7){
                            if($diannum<=10){
                                $ids = $ids.",".$orderid;
                            }
                        }else if($order['dian']==8){
                            if($diannum>=11){
                                $ids = $ids.",".$orderid;
                            }
                        }
                    }
                   
                   break;
                }
            }
        }
        $ids = trim($ids,",");
        //修改所有赢的订单
        if($ids){
            $orderModel->where("id in(".$ids.")")->update(array("is_winning"=>1));
        }
        
        //获取赢的订单的人，并发放
        $yong = db("config")->where("id=3")->find();
        $oList = $orderModel->field("sum(money) as money,user_id,is_winning,home_id")->where("is_winning=1 and num={$num} and order_type=0")->group("user_id")->select();
        foreach ($oList as $o){
            $countmoney = 0;
            $countmoney = $o['money']+($o['money']-($o['money']*$yong['values']));
            $countmoney = floor($countmoney);
            $userModel->where("id={$o['user_id']}")->setInc("user_money",$countmoney);
            $redisUser = redisd() -> HGet("user", $o['user_id']);
            $redisUser['user_money'] = $redisUser['user_money'] + $countmoney;
            redisd() -> HSet("user", $o['user_id'], $redisUser);
            
            
            $isRebate = db("rebate");
            
            $ptmoney = array(
                "user_id" => 0,
                "money"   => $o['money']*0.02,
                "buy_id"  => 0,
                "add_time"=> time(),
                "status" => 1
            );
            $isRebate -> insert($ptmoney);
            if($o['home_id']!=1&&$o['is_winning']==1){//其他房间的额
                $homes=redisd()->HGet('homes',$o['home_id']);//获取当前房间里面de信息
                $createid=redisd()->HGet('user',$homes['createid']);//
                if( $homes['createid']&&isset($createid)){//存在房主
                    //添加代理的钱
                    $createid['user_money']+=$o['money']*0.03;
                    $createid['com_money']+=$o['money']*0.03;
                    $createid=redisd()->HSet('user',$homes['createid'],$createid );
                    $userModel->where("id={$homes['createid']}")->update(array("user_money"=>$createid['user_money'],"com_money"=>$createid['com_money']));

                    $dlmoney = array(
                        "user_id" => $homes['createid'],
                        "money"   => $o['money']*0.03,
                        "buy_id"  => $o['user_id'],
                        "add_time"=> time()
                    );
                    $isRebate -> insert($dlmoney);
                }
                
            }
            
            
            
        }
        //计算庄家的信息和输赢
//         $homeModel = db("home");
//         $homeList = $homeModel->select();
        $homeList = redisd() -> HgetAll("homes");
        foreach ($homeList as $k => $home){
            $roleid = $home['role_user_id'];//庄家id
            if($roleid){
//                 $user = $userModel->where("id={$roleid}")->find();
                $user = redisd() -> HGet("user", $roleid);
                if($user){//机器人将不计算，人计算
                    $zmoney = $user['user_money'];//庄家钱
                    $ymoney = $orderModel->where("is_winning=1 and num={$num} and home_id={$k} and order_type=0")->sum("money");
                    $smoney = $orderModel->where("is_winning=0 and num={$num} and home_id={$k} and order_type=0")->sum("money");
                    $mon = ($zmoney+$smoney)-$ymoney;
                    //庄家赢钱扣分
                    $hm = 0;
                    if($smoney-$ymoney>0){
                        $kmoney = ($smoney-$ymoney)*$yong['values'];//庄家赢的钱
                        $mon = $mon-$kmoney;
                        $zzmoney = $smoney-$ymoney;
                        $hm = $home['rolemoney']+($zzmoney-($zzmoney*$yong['values']));
                        
                        $winmoney=$smoney-$ymoney;
                        $isRebate = db("rebate");
                        if($k!=1){//其他房间的额
                            $homes=redisd()->HGet('homes',$k);//获取当前房间里面de信息
                            $createid=redisd()->HGet('user',$homes['createid']);//
                            if( $homes['createid'] && isset($createid)){//存在房主
                                //添加代理的钱
                                $createid['user_money']+=$winmoney*0.03;
                                $createid['com_money']+=$winmoney*0.03;
                                $createid=redisd()->HSet('user',$homes['createid'],$createid );
                                $userModel->where("id={$homes['createid']}")->update(array("user_money"=>$createid['user_money'],"com_money"=>$createid['com_money']));

                                $dlmoney = array(
                                    "user_id" => $homes['createid'],
                                    "money"   => $winmoney*0.03,
                                    "buy_id"  => $roleid,
                                    "add_time"=> time()
                                );
                                $isRebate -> insert($dlmoney);
                            }
                        }
                        $ptmoney = array(
                            "user_id" => 0,
                            "money"   => $winmoney*0.02,
                            "buy_id"  => 0,
                            "add_time"=> time(),
                            "status" => 1
                        );
                        $isRebate -> insert($ptmoney);
                    }else{
                        $sm = $ymoney-$smoney;
                        $hm = $home['rolemoney']-$ymoney;
                    }
//                     $homeModel->where("id={$k}")->update(array("rolemoney"=>$hm));
                    //echo $homeModel->getLastSql()."\n";    
                    $redisHome = redisd() -> HGet("homes", $k);
                    $redisHome['rolemoney'] = $hm;
                    redisd() ->HSet("homes", $k, $redisHome);
                    $userModel->where("id={$roleid}")->update(array("user_money"=>$mon));
                    $redisUser = redisd() -> HGet("user", $roleid);
                    $redisUser['user_money'] = $mon;
                    redisd() -> HSet("user", $roleid, $redisUser);
                    
                }
            }
            
        }
        
        //计算输家
        $homeUsers = redisd() -> HgetAll("homeUser");
        foreach ($homeUsers as $k => $v){
            foreach ($v as $row){
                $res = explode("_", $row);
                if ($res[0] != "jq"){
                    $myUser = redisd() -> HGet("user", $row);
                    db("users") -> where("id={$row}") -> update(array("user_money"=>$myUser['user_money']));
                }
            }
        }
    }
    /**
     * 发放每个人的积分205` *n $worker
     */
    private function sendMoneyAll($worker){
        $orderModel = db("order");
        $num = getNum();
        $yong = db("config")->where("id=3")->find();
        $dianModel = db("dian");
        foreach ($worker->connections as $connection){
            //获得在先的每个人
            if(isset($connection->uid)&&isset($connection->homeid)){
                $dian = $dianModel->where("num={$num} and home_id={$connection->homeid}")->find();
                //获取缓存当中的  房间
                $home=redisd()->HGet('homes',$connection->homeid);
                if($home['role_user_id']==$connection->uid){
                    $ymoney = $orderModel->where("is_winning=1 and num={$num} and home_id={$connection->homeid} and order_type=0")->sum("money");
                    $smoney = $orderModel->where("is_winning=0 and num={$num} and home_id={$connection->homeid} and order_type=0")->sum("money"); 
                    $xianmoney = getmoney($connection->uid); //获取缓存剩余的钱
                    //$zmoney = $home['rolemoney'];
                    if($smoney>$ymoney){
                        $ymoney = $smoney-$ymoney;
                        $ymoney = $ymoney-($ymoney*$yong['values']);
                        $a = 2;
                    }else if($smoney<$ymoney){
                        $ymoney = $ymoney-$smoney;
                        $a = 3;
                    }else if($smoney==$ymoney){
                        $a = 4;
                        $ymoney=0;
                    }
                    $array = array(
                        "ws"=>82,
                        "iswin"=>$a,
                        "dian"=>$dian['dian'],
                        "money"=>$ymoney,
                        "yue"=>$xianmoney
                    );
                    $json = json_encode($array);
                    $connection->send($json);
                    continue;
                }
                //赢钱
                $order = $orderModel->field("sum(money) as money,is_winning")->where("user_id={$connection->uid} and num={$num} and home_id={$connection->homeid} and is_winning=1")->group("user_id")->find();
                $yymoney = $order['money'];                
                $yymoney = $yymoney-($yymoney*$yong['values']);
                //输钱
                $ssmoney = $orderModel->where("user_id={$connection->uid} and num={$num} and home_id={$connection->homeid} and is_winning=0")->sum("money");
                $a = 1;//为下注
                $money = 0;                
                if($yymoney==0&&$ssmoney==0){
                    
                }else{
                    if($yymoney>$ssmoney){
                        $money = $yymoney-$ssmoney;
                        $a = 2;
                    }elseif($yymoney<$ssmoney){
                        $money = $ssmoney-$yymoney;
                        $a = 3;
                    }else{
                        $money = 0;
                        $a=4;
                    }
                } 
                $ye = getmoney($connection->uid);
                $array = array(
                    "ws"=>82,
                    "iswin"=>$a,
                    "dian"=>$dian['dian'],
                    "money"=>$money,
                    "yue"=>$ye
                );
                $json = json_encode($array);
                $connection->send($json);
            }
        } 
    }
    
    
}
